package top.archiesean.proxy;

import com.alibaba.fastjson.JSON;
import top.archiesean.client.RpcClient;
import top.archiesean.common.RpcRequest;
import top.archiesean.common.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * @author ArchieSean
 * @description 客户端代理类： 创建代理对象
 * @date 2024-03-06
 */
public class RpcClientProxy {


    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1. 封装request请求对象
                        RpcRequest request = new RpcRequest();
                        request.setRequestId(UUID.randomUUID().toString());
                        request.setClassName(method.getDeclaringClass().getName());
                        request.setParameterTypes(method.getParameterTypes());
                        request.setMethodName(method.getName());
                        request.setParameters(args);
                        //2. 创建rpcClient对象
                        RpcClient rpcClient = new RpcClient("127.0.0.1", 8888);

                        try {
                            // 3.发送消息
                            Object result = rpcClient.send(JSON.toJSONString(request));

                            //4. 返回结果
                            RpcResponse response = JSON.parseObject(result.toString(), RpcResponse.class);
                            if (response.getError() != null) {
                                throw new RuntimeException(response.getError());
                            }

                            Object responseResult = response.getResult();
                            Object o = JSON.parseObject(responseResult.toString(), method.getReturnType());

                            return o;

                        } catch (Exception ex) {
                            throw ex;
                        } finally {
                            rpcClient.close();
                        }
                    }
                }
        );
    }


}
